package com.yunduo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.ServiceCode;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Good;
import com.yunduo.entity.GoodType;
import com.yunduo.entity.PFile;
import com.yunduo.entity.ShopGoods;
import com.yunduo.entity.vo.FileObj;
import com.yunduo.entity.vo.GoodQuery;
import com.yunduo.module.FileStore.FileStore;
import com.yunduo.service.GoodService;
import com.yunduo.service.GoodTypeService;
import com.yunduo.service.PFileService;
import com.yunduo.service.ShopGoodsService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  商品控制类
 * </p>
 *
 * @author ChengXin
 * @since 2023-07-12
 */
@RequiresRoles("user")
@RestController
@RequestMapping("/good")
public class GoodController {

    @Resource
    private GoodService goodService;
    @Resource
    private GoodTypeService goodTypeService;
    @Resource
    private FileStore fileStore;
    @Resource
    private PFileService pFileService;
    @Resource
    private ShopGoodsService shopGoodsService;

    //添加
    @PostMapping("/add")
    public CommonReturn addGood(@RequestBody Good good){
        Good isExist = goodService.getOne(new LambdaQueryWrapper<Good>().eq(Good::getName, good.getName()));
        if(isExist!=null){
            return CommonReturn.ERROR(ServiceCode.IS_EXIST);
        }
        boolean save = goodService.save(good);
        if (!save){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("good",good);
    }

    //删除
    @DeleteMapping("/delete/{id}")
    public CommonReturn deleteGood(@PathVariable("id") String id){
        Good good = goodService.getById(id);
        boolean isDelete = goodService.removeById(id);
        PFile file = pFileService.getFileByUrl(good.getCover());
        FileObj fileObj = YunDuoUtils.getFileObjForPFile(file);
        fileStore.deleteFile(fileObj);
        pFileService.removeById(file.getId());
        if (!isDelete){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //查询
    @GetMapping("/get/{id}")
    public CommonReturn getGood(@PathVariable("id") String id){
        Good good = goodService.getById(id);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("good",good);
    }

    //查询 批量查询商品
    @PostMapping("/gets")
    public CommonReturn getGoods(@RequestBody String[] ids){
        List<Good> good = (List<Good>) goodService.listByIds(Arrays.asList(ids));
        good.forEach(item -> {
            /**
             * 因为商品表没有表示是否上架,所以这里借用了detilimg字段 来表示是否上架
             */
            GoodType typeName = goodTypeService.getById(item.getType());
            item.setType(typeName.getType());
            ShopGoods one = shopGoodsService.getOne(new LambdaQueryWrapper<ShopGoods>().eq(ShopGoods::getGoodId, item.getId()));
            if(one.getSale()){
                item.setDetilImg("true");
            }else{
                item.setDetilImg("false");
            }


        });
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",good);
    }

    //修改
    @PostMapping("/update")
    public CommonReturn updateGood(@RequestBody Good good){
        if(good.getId() == null || StringUtils.isEmpty(good.getId())){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        goodService.updateById(good);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //商品分页查询
    @PostMapping("/page")
    public CommonReturn getShopByPageQuery(@RequestBody GoodQuery query){
        long current = query.getCurrentPage();
        long pageItem = query.getPageItems();
        Page<Good> pageGood = new Page<>(current,pageItem);
        LambdaQueryWrapper<Good> goodQuery = new LambdaQueryWrapper<>();
        goodQuery.likeRight(!StringUtils.isEmpty(query.getName()),Good::getName,query.getName());
        goodQuery.eq(!StringUtils.isEmpty(query.getType()),Good::getType,query.getType());
        goodQuery.ge(query.getPriceBegin()!=null && query.getPriceBegin()>0,Good::getPrice,query.getPriceBegin());
        goodQuery.le(query.getPriceEnd()!=null && query.getPriceEnd()>0,Good::getPrice,query.getPriceEnd());
        if(query.getCreateBegin() != null){
            LocalDateTime begin = YunDuoUtils.splitDateString(query.getCreateBegin());
            goodQuery.ge(Good::getGmtCreate,begin);
        }
        if(query.getCreateEnd() != null){
            LocalDateTime end = YunDuoUtils.splitDateString(query.getCreateEnd());
            goodQuery.le(Good::getGmtCreate,end);
        }
        goodService.page(pageGood,goodQuery);
        List<Good> records = pageGood.getRecords();
        Iterator<Good> goodIterator = records.iterator();
        while (goodIterator.hasNext()){
            Good next = goodIterator.next();
            GoodType type = goodTypeService.getById(next.getType());
            next.setType(type.getType());
        }
        HashMap<String,Object> goodList = new HashMap<>();
        goodList.put("list",records);
        goodList.put("listSize",records.size());
        goodList.put("total",pageGood.getTotal());
        goodList.put("current",pageGood.getCurrent());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS,goodList);
    }

    //批量删除
    @DeleteMapping("/deletes")
    public CommonReturn deletesGood(@RequestBody String[] ids){
        goodService.removeByIds(Arrays.asList(ids));
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //商品效果图的添加待完善
}
